/*
 * Copyright 2009 Red Hat, Inc.
 *
 * Red Hat licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
/**
 * Handles a server-side channel.
 *
 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
 *
 * @version $Rev: 2121 $, $Date: 2010-02-02 09:38:07 +0900 (Tue, 02 Feb 2010) $
 */

package de.tuberlin.dima.dkey.server;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import de.tuberlin.dima.dkey.client.GTree;


public class ServerHandler extends SimpleChannelUpstreamHandler {

	static Logger logger = Logger.getLogger(ServerHandler.class);

	static TreeDB treedb = null;


	public static void setDB(TreeDB tree){
		treedb = tree;
	}
	
	
    @Override
    public void handleUpstream(
            ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            logger.info(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    /**
     * This handles the incoming data and will call the appropriate functions and then
     * return what they return
     */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

    	//The request test
    	String request = e.getMessage().toString();

    	//What we will return
    	StringBuffer response = new StringBuffer();
    	
    	JsonParser parser = new JsonParser();
    	
    	String command = null;
    	
    	try {
    		command = parser.parse(request).getAsJsonObject().get("command").getAsString();
    	} catch (com.google.gson.JsonSyntaxException e1) {
    		logger.info("Got some crappy json:\n" +request );
    	}
    		
        // Generate and write a response.
        
        boolean close = false;
        
        if(command == null){
        	response.append("{\"response\": \"JSONERROR\"}");
        } else if (command.length() == 0) {
            response.append("{\"response\": \"emptystring\"}");
        
        } else if (command.equalsIgnoreCase("end")) { ////////////////////////////////////////////////////////////////
        	response.append("{\"response\": \"bye\"}\r\n");
            close = true;
        
        } else if(command.equalsIgnoreCase("newtree")){////////////////////////////////////////////////////////////////
        	
        	String returnval = treedb.addTreeJson(parser.parse(request).getAsJsonObject().get("data").toString());

        	response.append("{\"response\": \""+returnval+"\"}");
        
        } else if(command.equalsIgnoreCase("commit")){////////////////////////////////////////////////////////////////
        	try {
				treedb.saveDB(treedb.getDbName());
			} catch (IOException e1) {
				response.append("{\"response\": \"IOException\"}");
				e1.printStackTrace();
			}
        } else if(command.equalsIgnoreCase("search")){////////////////////////////////////////////////////////////////
        	GQuery query = new GQuery();
        	query.readJson(parser.parse(request).getAsJsonObject().get("data").toString());
        	LinkedList<Integer> results = query.execute(treedb);
        	response.append("{\"response\": "+results+ "}");
       
        } else if(command.equalsIgnoreCase("get")){////////////////////////////////////////////////////////////////
        	
        	//Add all the elements to a list so we can give them to the serialiser
        	LinkedList<Integer> keys = new LinkedList<Integer>();
        	for (JsonElement i : parser.parse(request).getAsJsonObject().get("data").getAsJsonArray()){
        		keys.add(i.getAsInt());
        	}
        	
        	response.append("{\"response\": "+treedb.serializeJson(keys)+ "}");
        } else {
        	response.append("{\"response\": \"commandnotknown\"}");
        }


        //Log and add a new line
        logger.info(response);
        response.append("\r\n");
        
        // We do not need to write a ChannelBuffer here.
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
        ChannelFuture future = e.getChannel().write(response.toString());
        // Close the connection after sending 'Have a good day!'
        // if the client has sent 'bye'.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.warn("Unexpected exception from downstream.",  e.getCause());
        e.getChannel().close();
    }
}
